package com.china08.yxyapi.service.manage.tec.teaching.homework.workcorrect.upd1.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workcorrect.upd1.Workcorrect1FindClassStuTaskController.ClassStuTaskReport;
import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workcorrect.upd1.Workcorrect1FindClassStuTaskController.Know;
import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workcorrect.upd1.Workcorrect1FindClassStuTaskController.RespModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workcorrect.upd1.Workcorrect1FindClassStuTaskController.SubjectiveQues;
import com.china08.yxyapi.entity.mg.homework.HomeworkKnowReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskClass;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.repository.mg.homework.HomeworkKnowReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskClassRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.workcorrect.upd1.HomeworkCorrect1Service;

@Service
public class HomeworkCorrect1ServiceImpl implements HomeworkCorrect1Service {

    @Autowired
    HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Autowired
    HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    HomeworkTaskClassRepository homeworkTaskClassRepository;

    @Autowired
    HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    @Autowired
    HomeworkKnowReportRepository homeworkKnowReportRepository;

    @Override
    public RespModel convertRespModel(HomeworkTaskClass homeworkTaskClass, List<HomeworkTaskReport> homeworkTaskReports,
            List<HomeworkTaskReportQues> homeworkTaskReportQues1, List<HomeworkTaskReportQues> homeworkTaskReportQues2,
            Integer count0bjective, List<HomeworkTaskQues> homeworkTaskQuesList) {
        // return
        RespModel respModel = new RespModel();
        List<ClassStuTaskReport> classStuTaskReports = new ArrayList<ClassStuTaskReport>();
        // 通知类作业作答处理
        Map<String, HomeworkTaskReportQues> stuNotifys = new HashMap<String, HomeworkTaskReportQues>();
        homeworkTaskReportQues2.forEach(homeworkTaskReportQues -> {
            stuNotifys.put(homeworkTaskReportQues.getStudentId(), homeworkTaskReportQues);
        });
        // 主观题学生作答
        Map<String, HomeworkTaskReportQues> stuQuesIdSubjectives = new HashMap<String, HomeworkTaskReportQues>();
        homeworkTaskReportQues1.forEach(homeworkTaskReportQues -> {
            stuQuesIdSubjectives.put(homeworkTaskReportQues.getStudentId() + homeworkTaskReportQues.getQuesId(),
                    homeworkTaskReportQues);
        });
        // 获取主观题题干
        List<HomeworkTaskQues> homeworkTaskQuesLst = homeworkTaskQuesRepository
                .findByTaskIdAndQuesType(homeworkTaskClass.getTaskId(), "2");
        // 基本信息
        respModel.taskId = homeworkTaskClass == null ? "" : homeworkTaskClass.getTaskId();
        respModel.taskName = homeworkTaskClass == null ? "" : homeworkTaskClass.getTitle();
        respModel.grade = "";
        respModel.className = homeworkTaskClass == null ? "" : homeworkTaskClass.getClassName();
        respModel.is0bjective = count0bjective != null && count0bjective > 0;
        // 客观题-答对、答错（几道）
        List<String> questionTypes = new ArrayList<String>();
        questionTypes.add("0");
        questionTypes.add("1");
        // return
        List<ClassStuTaskReport> classStuTaskReportsCopy = new ArrayList<ClassStuTaskReport>();
        homeworkTaskReports.forEach(homeworkTaskReport -> {
            ClassStuTaskReport classStuTaskReport = new ClassStuTaskReport();
            classStuTaskReport.taskId = homeworkTaskReport.getTaskId();
            classStuTaskReport.classId = homeworkTaskReport.getClassId();
            classStuTaskReport.className = homeworkTaskReport.getClassName();
            classStuTaskReport.studentId = homeworkTaskReport.getStudentId();
            classStuTaskReport.studentNick = homeworkTaskReport.getStudentNick();
            classStuTaskReport.studentImg = this.avatar(homeworkTaskReport.getAvatar());
            classStuTaskReport.statusOfFinished = homeworkTaskReport.getStatusOfFinished();
            // 客观题答对，答错多少道题
            if (count0bjective != null && count0bjective > 0) {
                Integer count = homeworkTaskReportQuesRepository.countByTaskIdAndAndQuestionTypeInAndPassedAndStudentId(
                        homeworkTaskClass.getTaskId(), questionTypes, 1, homeworkTaskReport.getStudentId());
                classStuTaskReport.exactnessNumber = count == null ? 0 : count;
                classStuTaskReport.wrongNumber = count == null ? 0 : count0bjective - count;
            } else {
                classStuTaskReport.exactnessNumber = null;
                classStuTaskReport.wrongNumber = null;
            }
            // 通知类试题
            HomeworkTaskReportQues taskReQues = stuNotifys.get(homeworkTaskReport.getStudentId());
            classStuTaskReport.isNotify = taskReQues != null ? true : false;
            classStuTaskReport.notifyQuesId = taskReQues == null ? null : taskReQues.getQuesId();
            classStuTaskReport.notifyQuesOrder = taskReQues == null ? null : taskReQues.getOrder();
            classStuTaskReport.notifyMark = taskReQues == null ? null : taskReQues.getNotifyPassed();
            classStuTaskReport.notifyAnswerText = taskReQues == null ? null : taskReQues.getAnswerText();
            classStuTaskReport.notifyAnswerImgs = taskReQues == null ? null : taskReQues.getAnswerImgs();
            classStuTaskReport.notifyTaskReportQuesId = taskReQues == null ? null : taskReQues.getId();
            classStuTaskReport.notifyQuesContent = (homeworkTaskQuesLst != null && homeworkTaskQuesLst.size() > 0)
                    ? homeworkTaskQuesLst.get(0).getQuesContent() : null;
            classStuTaskReport.notifyQuesImage = (homeworkTaskQuesLst != null && homeworkTaskQuesLst.size() > 0)
                    ? homeworkTaskQuesLst.get(0).getQuesImage() : new ArrayList<String>();
            classStuTaskReport.notifyQuesArticle = (homeworkTaskQuesLst != null && homeworkTaskQuesLst.size() > 0)
                    ? homeworkTaskQuesLst.get(0).getQuesArticle() : new ArrayList<>();
            classStuTaskReport.notifyFinishTime = getDuration(taskReQues == null ? null : taskReQues.getDuration());
            // 主观题试题
            List<SubjectiveQues> subjectiveQues = new ArrayList<>();
            homeworkTaskQuesList.forEach(homeworkTaskQues -> {
                HomeworkTaskReportQues taskReportQues = stuQuesIdSubjectives
                        .get(homeworkTaskReport.getStudentId() + homeworkTaskQues.getQuesId());
                SubjectiveQues subjectiveQue = new SubjectiveQues();
                subjectiveQue.quesType = taskReportQues == null ? null : taskReportQues.getQuestionType();
                subjectiveQue.quesId = taskReportQues == null ? null : taskReportQues.getQuesId();
                subjectiveQue.quesOrder = taskReportQues == null ? null : taskReportQues.getOrder();
                subjectiveQue.mark = taskReportQues == null ? null : taskReportQues.getMark();
                subjectiveQue.answerText = taskReportQues == null ? null : taskReportQues.getAnswerText();
                subjectiveQue.answerImgs = taskReportQues == null ? null : taskReportQues.getAnswerImgs();
                subjectiveQue.taskReportQuesId = taskReportQues == null ? null : taskReportQues.getId();
                subjectiveQue.wrongKnowIdLst = (taskReportQues == null || taskReportQues.getWrongKnowIdLst() == null
                        || taskReportQues.getWrongKnowIdLst().size() == 0) ? new ArrayList<>()
                                : taskReportQues.getWrongKnowIdLst();
                subjectiveQue.exactnessKnowIdLst = (taskReportQues == null
                        || taskReportQues.getExactnessKnowIdLst() == null
                        || taskReportQues.getExactnessKnowIdLst().size() == 0) ? new ArrayList<>()
                                : taskReportQues.getExactnessKnowIdLst();
                List<Know> knows = new ArrayList<>();
                if (taskReportQues != null && taskReportQues.getKnowIdLst() != null
                        && taskReportQues.getKnowIdLst().size() > 0 && taskReportQues.getKnowNameLst() != null
                        && taskReportQues.getKnowNameLst().size() > 0) {
                    for (int i = 0; i < taskReportQues.getKnowNameLst().size(); i++) {
                        Know know = new Know();
                        know.id = taskReportQues.getKnowIdLst().get(i);
                        know.name = taskReportQues.getKnowNameLst().get(i);
                        knows.add(know);
                    }
                }
                subjectiveQue.finishTime = getDuration(taskReportQues == null ? null : taskReportQues.getDuration());
                subjectiveQue.knows = knows;
                subjectiveQues.add(subjectiveQue);
            });
            classStuTaskReport.subjectiveQuesList = subjectiveQues;
            classStuTaskReportsCopy.add(classStuTaskReport);
        });
        // 下面是排序
        // 手工排序，按照学生完成时间排序，-1-逾期未提交,0-未做,3-答题中 排在后面，1-完成 ,2-已批阅排在前面
        List<ClassStuTaskReport> list1 = new ArrayList<>(); // 1-完成 ,2-已批阅
        List<ClassStuTaskReport> list2 = new ArrayList<>(); // 3-答题中
        List<ClassStuTaskReport> list3 = new ArrayList<>(); // -1-逾期未提交,0-未做
        classStuTaskReportsCopy.forEach(classStuTaskReport -> {
            if (classStuTaskReport.statusOfFinished == 1 || classStuTaskReport.statusOfFinished == 2) {
                list1.add(classStuTaskReport);
            } else if (classStuTaskReport.statusOfFinished == 3) {
                list2.add(classStuTaskReport);
            } else if (classStuTaskReport.statusOfFinished == -1 || classStuTaskReport.statusOfFinished == 0) {
                list3.add(classStuTaskReport);
            }
        });
        list1.forEach(classStuTaskReport -> {
            classStuTaskReports.add(classStuTaskReport);
        });
        list2.forEach(classStuTaskReport -> {
            classStuTaskReports.add(classStuTaskReport);
        });
        list3.forEach(classStuTaskReport -> {
            classStuTaskReports.add(classStuTaskReport);
        });
        respModel.classStuTaskReports = classStuTaskReports;
        return respModel;
    }

    @Override
    public void correct(String taskId, String classId, String studentId) {
        // 本次任务总题数
        Integer total = homeworkTaskQuesRepository.countByTaskId(taskId);
        if (total != null && total > 0) {
            // 本次任务单选题、多选题数量
            List<String> quesTypes = new ArrayList<>();
            quesTypes.add("0");
            quesTypes.add("1");
            Integer total0_1 = homeworkTaskQuesRepository.countByTaskIdAndQuesTypeIn(taskId, quesTypes);
            // 本次任务只有选择题
            if (total0_1 >= total) {
                // 获取学生作业记录
                HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository
                        .findTop1ByTaskIdAndClassIdAndStudentId(taskId, classId, studentId);
                // 获取班级任务
                HomeworkTaskClass homeworkTaskClassz = homeworkTaskClassRepository.findTop1ByTaskIdAndClassId(taskId,
                        classId);
                try {
                    // 更新学生任务完成状态为 -> 批阅
                    homeworkTaskReport.setStatusOfFinished(2);
                    homeworkTaskReportRepository.save(homeworkTaskReport);
                    // 更新班级批阅人数
                    homeworkTaskClassz.setMarkingOfStudent(homeworkTaskReportRepository
                            .countByClassIdAndTaskIdAndStatusOfFinished(classId, taskId, 2));
                    homeworkTaskClassRepository.save(homeworkTaskClassz);
                    // 正确率统计
                    this.stuTaskAccuracy(taskId, classId, studentId);
                    // 知识点状态统计
                    this.stuTaskPointRate(taskId, classId, studentId);
                } catch (Exception e) {
                }
            } else { // 本次任务有 主观题或通知作业
                // 本次任务需要批阅试题数量
                Integer total2_3_4_ = homeworkTaskQuesRepository.countByTaskIdAndQuesTypeNotIn(taskId, quesTypes);
                if (total2_3_4_ != null && total2_3_4_ > 0) {
                    // 批阅通知类试题数量
                    Integer total2 = homeworkTaskReportQuesRepository
                            .countByClassIdAndStudentIdAndTaskIdAndQuestionTypeAndNotifyPassedNot(classId, studentId,
                                    taskId, "2", null);
                    total2 = total2 == null ? 0 : total2;
                    // 批阅主观题数量
                    quesTypes.add("2");
                    Integer total3_4 = homeworkTaskReportQuesRepository
                            .countByClassIdAndStudentIdAndTaskIdAndQuestionTypeNotInAndMarkNot(classId, studentId,
                                    taskId, quesTypes, null);
                    total3_4 = total3_4 == null ? 0 : total3_4;
                    // 判断教师批阅学生试题数量是否等于本次需要批阅试题数量
                    if ((total2 + total3_4) == total2_3_4_) {
                        // 获取学生作业记录
                        HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository
                                .findTop1ByTaskIdAndClassIdAndStudentId(taskId, classId, studentId);
                        // 获取班级任务
                        HomeworkTaskClass homeworkTaskClassz = homeworkTaskClassRepository
                                .findTop1ByTaskIdAndClassId(taskId, classId);
                        try {
                            // 更新学生任务完成状态为 -> 批阅
                            homeworkTaskReport.setStatusOfFinished(2);
                            homeworkTaskReportRepository.save(homeworkTaskReport);
                            // 更新班级批阅人数
                            homeworkTaskClassz.setMarkingOfStudent(homeworkTaskReportRepository
                                    .countByClassIdAndTaskIdAndStatusOfFinished(classId, taskId, 2));
                            homeworkTaskClassRepository.save(homeworkTaskClassz);
                            // 正确率统计
                            this.stuTaskAccuracy(taskId, classId, studentId);
                            // 知识点状态统计
                            this.stuTaskPointRate(taskId, classId, studentId);
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
    }

    @Override
    public void stuTaskAccuracy(String taskId, String classId, String studentId) {
        try {
            // 获取非通知类试题，作业试题数量
            Integer total = homeworkTaskQuesRepository.countByTaskIdAndQuesTypeNot(taskId, "2");
            // 学生正确分值占得比重
            Double weight = 0d;
            if (total != null && total > 0) {
                // 获取学生所有答题记录
                List<HomeworkTaskReportQues> homeworkTaskReportQues = homeworkTaskReportQuesRepository
                        .findByStudentIdAndTaskIdAndClassId(studentId, taskId, classId);
                if (homeworkTaskReportQues != null && homeworkTaskReportQues.size() > 0) {
                    for (HomeworkTaskReportQues taskReportQues : homeworkTaskReportQues) {
                        // 排除通知类试题
                        if (taskReportQues.getQuestionType() != null && !taskReportQues.getQuestionType().equals("2")) {
                            // 单选题，多选题
                            if (taskReportQues.getQuestionType().equals("0")
                                    || taskReportQues.getQuestionType().equals("1")) {
                                // 是否正确 0-错误 , 1-正确 （单选，多选）
                                Integer passed = taskReportQues.getPassed();
                                if (passed != null && passed == 1) {
                                    weight++;
                                }
                            }
                            // 填空题，简答题
                            if (taskReportQues.getQuestionType().equals("3")
                                    || taskReportQues.getQuestionType().equals("4")) {
                                // 总分5分，每一分权重占 0.2
                                Integer mark = taskReportQues.getMark();
                                if (mark != null) {
                                    weight = weight + mark.doubleValue() * 0.2;
                                }
                            }
                        }
                    }
                }
            }
            if (total != null && total > 0 && weight > 0) {
                // 更新学生正确率
                HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository
                        .findTop1ByTaskIdAndClassIdAndStudentId(taskId, classId, studentId);
                if (homeworkTaskReport != null) {
                    // 计算出正确率，并且乘以100
                    Double accuracy = (weight / total.doubleValue()) * 100;
                    homeworkTaskReport.setRightRate(accuracy);
                    homeworkTaskReportRepository.save(homeworkTaskReport);
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void stuTaskPointRate(String taskId, String classId, String studentId) {
        try {
            // 查询这个学生数据是否生成过
            Integer count = homeworkKnowReportRepository.countByTaskIdAndClassIdAndStudentId(taskId, classId,
                    studentId);
            String schoolId = "";
            // 数据没有生成
            if (count == null || count == 0) {
                // 储存基础知识点
                Map<Integer, String> knowMap = new HashMap<Integer, String>();
                List<Integer> knowAll = new ArrayList<>();
                List<Integer> exactnessKnow = new ArrayList<>();
                // 获取学生所有答题记录
                List<HomeworkTaskReportQues> taskReportQues = homeworkTaskReportQuesRepository
                        .findByStudentIdAndTaskIdAndClassId(studentId, taskId, classId);
                if (taskReportQues != null && taskReportQues.size() > 0) {
                    // 获取学校
                    schoolId = taskReportQues.get(0).getSchoolId();
                    // 数据遍历
                    for (HomeworkTaskReportQues reportQues : taskReportQues) {
                        // 基础知识点
                        List<Integer> knowIds = reportQues.getKnowIdLst();
                        List<String> knowNames = reportQues.getKnowNameLst();
                        if (knowIds != null && knowIds.size() > 0) {
                            for (int i = 0; i < knowIds.size(); i++) {
                                knowMap.put(knowIds.get(i), knowNames.get(i));
                            }
                        }
                        // 所有出现的知识点统计
                        if (knowIds != null && knowIds.size() > 0) {
                            knowAll.addAll(knowIds);
                        }
                        // 正确的知识点统计
                        // ## 单选题,多选题
                        if (reportQues.getQuestionType() != null
                                && (reportQues.getQuestionType().equals("0")
                                        || reportQues.getQuestionType().equals("1"))
                                && reportQues.getPassed() != null && reportQues.getPassed() == 1) {
                            if (knowIds != null && knowIds.size() > 0) {
                                exactnessKnow.addAll(knowIds);
                            }
                        }
                        // ## 填空题,简答题
                        if (reportQues.getQuestionType() != null && (reportQues.getQuestionType().equals("3")
                                || reportQues.getQuestionType().equals("4")) && reportQues.getMark() != null) {
                            if (reportQues.getExactnessKnowIdLst() != null
                                    && reportQues.getExactnessKnowIdLst().size() > 0) {
                                exactnessKnow.addAll(reportQues.getExactnessKnowIdLst());
                            }
                        }
                    }
                }
                // 循环所有知识点
                if (knowMap != null && knowMap.size() > 0) {
                    // list 保存数据使用
                    List<HomeworkKnowReport> homeworkKnowReports = new ArrayList<>();
                    // 生成需要保存的数据
                    Set<Integer> knowIds = knowMap.keySet();
                    for (Integer knowId : knowIds) {
                        // 掌握比率计算
                        double rate = 0d;
                        Integer knowIdTotal = Collections.frequency(knowAll, knowId);
                        Integer exactnessKnowTotal = Collections.frequency(exactnessKnow, knowId);
                        if (knowIdTotal > 0 && exactnessKnowTotal > 0) {
                            rate = (exactnessKnowTotal.doubleValue() / knowIdTotal.doubleValue()) * 100;
                        }
                        // 数据对象
                        HomeworkKnowReport HomeworkKnowReport = new HomeworkKnowReport();
                        HomeworkKnowReport.setClassId(classId);
                        HomeworkKnowReport.setKnowId(knowId);
                        HomeworkKnowReport.setKnowName(knowMap.get(knowId));
                        HomeworkKnowReport.setRate(rate);
                        HomeworkKnowReport.setSchoolId(schoolId);
                        HomeworkKnowReport.setStudentId(studentId);
                        HomeworkKnowReport.setTaskId(taskId);
                        homeworkKnowReports.add(HomeworkKnowReport);
                    }
                    // 数据库保存
                    homeworkKnowReportRepository.save(homeworkKnowReports);
                }
            }
        } catch (Exception e) {
        }
    }

    // 时间转化
    private String getDuration(Integer integer) {
        if (integer == null || integer == null) { return ""; }
        long time = integer;
        long miao = time % 60; // 秒
        time = time / 60; // 转化为 分
        long shi = time / 60; // 抓换为 时
        long fen = time % 60; // 抓换为 分
        return shi + "时" + fen + "分" + miao + "秒";
    }

    private String avatar(String avatar) {
        if (avatar != null && avatar.trim().length() > 0 && !avatar.startsWith("http") && !avatar.startsWith("https")) {
            avatar = "https://yxcsp.91yunxiao.com/yxcsp/pull/" + avatar;
        }
        return avatar;
    }
}
